package com.tenny.bookstore.dao.impl;



import com.tenny.bookstore.bean.Book;
import com.tenny.bookstore.dao.BookDao;
import com.tenny.bookstore.exception.DaoException;
import com.tenny.bookstore.util.DBCPUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by Tenney on 2017/3/16.
 */
public class BookDaoImpl extends BookDao<Book> {

    private QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());

    @Override
    public List<Book> findPageBooks(int startIndex, int offset) {
        try{
            return qr.query("select * from book limit ?,?", new BeanListHandler<Book>(Book.class),startIndex,offset);
        }catch(Exception e){
            throw new DaoException(e);
        }
    }

    @Override
    public int findAllBooksNumber() {
        try{
            Object obj = qr.query("select count(*) from book", new ScalarHandler(1));
            Long num = (Long)obj;
            return num.intValue();
        }catch(Exception e){
            throw new DaoException(e);
        }
    }

    @Override
    public List<Book> findAll() {
        try {
            return qr.query("select * from book", new BeanListHandler<Book>(Book.class));
        } catch (SQLException e) {
            throw new DaoException(e);
        }
    }

    @Override
    public void save(Book book) {
        System.out.print(book.toString());
        try{
            qr.update("insert into book (id,name,price,author,path,filename,description,categoryId) values (?,?,?,?,?,?,?,?)",
                    book.getId(),
                    book.getName(),
                    book.getPrice(),
                    book.getAuthor(),
                    book.getPath(),
                    book.getPhotoFileName(),
                    book.getDescription(),
                    book.getCategoryId());
        }catch(Exception e){
            throw new DaoException(e);
        }

    }

    @Override
    public Book findById(String id) {
        try{
            return qr.query("select * from book where id=?", new BeanHandler<Book>(Book.class),id);
        }catch(Exception e){
            throw new DaoException(e);
        }
    }
}
